package com.yqg.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;

/**
 * @author suzhuang
 * @ClassName: MyController
 * @Function: TODO
 * @Date: 2023/5/12 21:38
 */
@RestController
public class MyController {
    // 定义全局变量
    private static String globalVar = "Hello, World!";

    @RequestMapping("/set")
    public String setGlobalVar(@RequestParam("value") String value) {
        // 线程安全地更新全局变量
        synchronized (MyController.class) {
            globalVar = value;
        }
        return "OK";
    }

    @RequestMapping("/get")
    public String getGlobalVar() {
        return globalVar;
    }

    @GetMapping("/thread")
    public String threadMethod() {
            // 在线程中访问全局变量
            Thread thread = new Thread(() -> {
                    synchronized (MyController.class) {
                        globalVar = "Hello, Thread!";
                    }

            });
            thread.start();
            try {
                thread.join(); // 等待线程执行完毕
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        return globalVar;
    }
}

